package top.eggcode.template.log;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import top.eggcode.common.log.Record;
import top.eggcode.spring.AsyncExecutor;
import top.eggcode.system.client.LogClientService;
import top.eggcode.system.client.model.FuncLog;

/**
 * Title: 功能记录
 * Description: TODO
 * Date: 2021/5/25 9:37
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Aspect
@Component
@AllArgsConstructor
public class FuncRecordAspect {

    private final LogClientService clientService;

    private final AsyncExecutor executor;

    @Pointcut("@annotation(top.eggcode.common.log.Record)")
    public void pointcut() {
    }

    @Around("pointcut()&&@annotation(record)")
    public Object doAround(ProceedingJoinPoint point, Record record) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = point.proceed();
        long executionTime = System.currentTimeMillis() - start;
        String params = JSON.toJSONString(point.getArgs());
        String classMethod = point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();

        FuncLog log = new FuncLog();
        log.setPath(classMethod);
        log.setTimeSpent(executionTime);
        log.setName(record.name());
        log.setModule(record.module());
        if (record.param()) {
            log.setParams(params);
        }

        if (record.param()) {
            log.setResult(JSON.toJSONString(proceed));
        }
        executor.commit(clientService::saveToFunction, log);
        return proceed;
    }
}
